package com.ggqq.controller;


import com.ggqq.entity.Message;
import com.ggqq.entity.User;
import com.ggqq.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * 留言 控制器
 * */

@Controller
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Value("${message.avatar}")
    private String avatar;//设置留言的默认头像

    //返回留言页面
    @GetMapping("/message")
    public String message(){
        return "message";
    }

    //查询留言
    @GetMapping("/messagecomment")
    public String message(Model model){
        List<Message> messages = messageService.listMessage();
        model.addAttribute("messages",messages);
        return "message :: messageList";
    }

    //新增留言
    @PostMapping("/message")
    public String post(Message message, HttpSession session,Model model) {
        User user = (User) session.getAttribute("user");
        //设置头像
        if(user != null){
            message.setAvatar(user.getAvatar());
            message.setAdminMessage(true);
        }else{
            message.setAvatar(avatar);
        }

        if(message.getParentMessage().getId() != null){
            message.setParentMessageId(message.getParentMessage().getId());
        }
        messageService.saveMessage(message);
        List<Message> messages = messageService.listMessage();
        model.addAttribute("messages",messages);

        return "message :: messageList";
    }

    //删除留言
    @GetMapping("/messages/{id}/delete")
    public String delete(@PathVariable Long id){
        messageService.deleteMessage(id);
        return "redirect:/message";
    }
}
